#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <linux/un.h>
#include "ipc_socket.h"
#include "modbus_ipc.h"

static void modbus_TLV_process(void)
{
    char *dataPtr = NULL;
    modbus_common *modbusData = NULL;
    int size = 0;
    int recvLen = 0;

    size = sizeof(modbus_common);
    dataPtr = (char *)malloc(size);
    memset(dataPtr, 0, size);
    //处理MODBUS的TLV数据
    recvLen = get_TLV_data(MODBUS_IPC, (void *)dataPtr, size);
    while(recvLen) {
        if (recvLen >= sizeof(modbus_common)) {
            modbusData = (modbus_common *)dataPtr;
            printf("Type = %d Addr = %d Data = %d\n", modbusData->type, modbusData->addr, modbusData->value);
        }
        memset(dataPtr, 0, size);
        recvLen = get_TLV_data(MODBUS_IPC, (void *)dataPtr, size);
    }
    free(dataPtr);
}

static void *input_thread_handler(void *param)
{
    int ret = 0;
    int addr = 0;
    int value = 0;
    int opt = 0;
    modbus_common modbusData = {0};
    while(is_exit()) {
        printf("Plese input addr:");
        scanf("%d", &addr);
        printf("Read[%d] or write[%d]:", MODBUS_READ, MODBUS_WRITE);
        scanf("%d", &opt);
        if (opt == MODBUS_WRITE) {
            printf("Please input Value:");
            scanf("%d", &value);
        }
        modbusData.type = opt;
        modbusData.addr = addr;
        modbusData.value = value;
        send_TLV_data(MODBUS_IPC, (void *)&modbusData, sizeof(modbus_common));
    }
    ret = 0;
    printf("Exit thread\n");
    pthread_exit(&ret);
}


int main()
{
    int fd = -1;
    int ret = -1;
    pthread_t thread_socket;
    pthread_t thread_input;
    fd = client_socket_init();
    if(fd == -1) {
        exit(0);
    }
    
    if(socket_recv_thread(&thread_socket, fd) == -1) {
        perror("Create thread failed");
        close(fd);
    }

    ret = socketfd_bind(MODBUS_IPC, fd);
    if (ret != fd) {
        perror("Socket fd bind failed\n");
    }

    //创建一个线程接收终端输入
    ret = pthread_create(&thread_input, NULL, input_thread_handler, NULL);
    if(ret != 0) {
        perror("thread create");
        ret = -1;
    }

    while(is_exit()) {   
        modbus_TLV_process();
    }
    socketfd_unbind(MODBUS_IPC);
    close(fd);
    return 0;
}
